import { contextBridge } from 'electron';
import { electronAPI } from '@electron-toolkit/preload';

// eslint-disable-next-line @typescript-eslint/no-var-requires
const os = require('os');
// eslint-disable-next-line @typescript-eslint/no-var-requires
const http = require('http');

// Custom APIs for renderer
const api = {
  server: undefined,
  getNetworkInterfaces: (): string[] => {
    const interfaces = os.networkInterfaces();
    const ipList: string[] = [];
    for (const ifaceKey in interfaces) {
      for (const interfaceInfo of interfaces[ifaceKey]) {
        if (interfaceInfo.family === 'IPv4' && !interfaceInfo.internal) {
          ipList.push(interfaceInfo.address);
        }
      }
    }
    return ipList;
  },
  createHttpService: (
    ip: string,
    port: number,
    log: (str: string) => void,
    request: (method: string, url: string, type: string, body: string) => void,
    success: () => void,
    error: (err: Error) => void
  ) => {
    const server = http.createServer();
    server.on('request', (req: Request, res: Response) => {
      // 读取请求体
      let data = '';
      // @ts-ignore
      req.on('data', (chunk) => {
        data += chunk;
      });
      // @ts-ignore
      req.on('end', () => {
        request(req.method, req.url, req.headers['content-type'], data);
      });
      // @ts-ignore
      res.writeHead(200, {
        'Content-Type': 'application/json;charset=utf-8',
        'access-control-allow-origin': '*'
      });
      // @ts-ignore
      res.end(
        JSON.stringify({
          code: 200
        })
      );
    });
    server.listen(port, ip, () => {
      log(`服务器开启成功，服务器地址: http://${ip}:${port}`);
      success();
    });
    server.on('error', (err: Error) => {
      // @ts-ignore
      if (err.code === 'EADDRINUSE') {
        log(`端口:${port}被占用,请更换占用端口`);
      }
      error(err);
    });
    return {
      // @ts-ignore
      close: () => {
        server && server.removeAllListeners();
        server &&
          server.close(() => {
            log('服务接口关闭');
          });
      }
    };
  },
  sendHttpRequest: (
    url: string,
    options: {
      method: string;
      headers: {
        [key: string]: never;
      };
      timeout: number;
    },
    body: string,
    callback: (data: { code: number; msg: string; data: string }) => void
  ) => {
    const req = http.request(url, options, (res) => {
      let data = '';
      // 接收数据
      res.on('data', (chunk) => {
        data += chunk;
      });
      // 数据接收完毕
      res.on('end', () => {
        callback({
          code: 200,
          msg: 'ok',
          data: data
        });
      });
    });
    // 错误处理
    req.on('error', (e) => {
      console.error(e);
      console.error(`problem with request: ${e.message}`);
      callback({
        code: 500,
        msg: e.message,
        data: ''
      });
    });
    if (options.method === 'POST') {
      req.write(body);
    }
    // 结束请求
    req.end();
    return {
      cancel: () => {
        req.destroy();
      }
    };
  }
};

// Use `contextBridge` APIs to expose Electron APIs to
// renderer only if context isolation is enabled, otherwise
// just add to the DOM global.
if (process.contextIsolated) {
  try {
    contextBridge.exposeInMainWorld('electron', electronAPI);
    contextBridge.exposeInMainWorld('api', api);
  } catch (error) {
    console.error(error);
  }
} else {
  // @ts-ignore (define in dts)
  window.electron = electronAPI;
  // @ts-ignore (define in dts)
  window.api = api;
}
